using UnityEngine;
using UnityEngine.UI;
using QFramework;
using DG.Tweening;

namespace HareGame
{
    public class UIDialogData : UIPanelData
    {
        public string Key;
    }
    public partial class UIDialog : UIBase
    {
        Tween msgSpeed;
        [Header("显示完整文本耗时")]
        public float Speed = 2;
        public bool IsComplete;
        public bool CanNext;

        protected override void OnInit(IUIData uiData = null)
        {
            base.OnInit();
            mData = uiData as UIDialogData ?? new UIDialogData();
        }

        protected override void OnOpen(IUIData uiData = null)
        {
            base.OnOpen();

            Dialog.DOFade(1, 0.2f).SetUpdate(true).SetEase(Ease.Linear).OnComplete(() =>
            {
                ShowMsg(mData.Key);
            });
        }

        protected override void OnClose()
        {
            base.OnClose();
        }

        public void ShowMsg(string key)
        {
            if (msgSpeed != null)
                msgSpeed.Kill();

            IsComplete = false;
            CanNext = false;
            txtMsg.text = "";
            string msg = GameEntry.Localization.GetValue(key);
            msgSpeed = txtMsg.DOText(msg, Speed).SetUpdate(true).OnComplete(() =>
            {
                IsComplete = true;
            });
        }

        private void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                if (IsComplete)
                {
                    CanNext = true;
                }
                if (msgSpeed != null)
                {
                    msgSpeed.Kill(true);
                    msgSpeed = null;
                }
            }
        }
    }
}
